package cn.yunhe.servlet;

import cn.yunhe.pojo.NewsDemo;
import cn.yunhe.pojo.NumNews;
import cn.yunhe.pojo.PageDemo;
import cn.yunhe.service.NewsService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class QueryLimitNewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String keyword = request.getParameter("keyword");
        System.out.println(keyword);
        String pagenum = request.getParameter("pageno");
        PageDemo pagedemo = new PageDemo();
        if (pagenum == null) {
            pagenum = "1";
        }

        int pageNo = Integer.parseInt(pagenum);

        NewsService newsService = new NewsService();
        pagedemo.setKeyword(keyword);
        int counts = newsService.getcounts(pagedemo);
        counts = (counts % PageDemo.getPageSize() == 0 ? counts / PageDemo.getPageSize() : counts / PageDemo.getPageSize() + 1);
        NumNews numnews = new NumNews(pageNo, counts);
        int pageStartNo = pageNo - 1;

        if(counts>0){
            if (pageStartNo < 0) {
                pageStartNo = 0;
            } else if (pageStartNo > counts) {
                pageStartNo = counts - 1;
            }
        }

        int pageStart = pageStartNo * PageDemo.getPageSize();
        pagedemo.setPageStart(pageStart);
        pagedemo.setKeyword(keyword);
        List<NewsDemo> listnews = newsService.getNewsByLimit(pagedemo);

        HttpSession session = request.getSession();
        if (listnews != null && listnews.size() > 0) {
            session.setAttribute("keyword", keyword);
            request.setAttribute("listnews", listnews);
            request.setAttribute("numnews", numnews);
            request.getRequestDispatcher("mainnews.jsp").forward(request, response);
        }else{
            response.sendRedirect("QueryLimitNewsServlet");
        }
    }
}
